package example.demo.datasouce;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;


import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

//@Order(-50),这个在invoke-bean-factory-processor才会有效
@Slf4j
@Configuration
//必须在{"db1","db2","db3"}之后去实例化多数据源的bean【下面的-DataSource dynamicDataSource】
@DependsOn({"db1", "db2", "db3"})
public class DBConfig {

//    @Resource(name = "db1")
//    DataSource db1;
//    @Resource(name = "db2")
//    DataSource db2;
//    @Resource(name = "db3")
//    DataSource db3;

    @Bean
    @Primary
    public DataSource dynamicDataSource(@Qualifier("db1") DataSource db1,
                                        @Qualifier("db2") DataSource db2,
                                        @Qualifier("db3") DataSource db3) {
        Map<Object, Object> targetDataSources = new HashMap<>();
        DBTypeEnum db11 = DBTypeEnum.db1;
        targetDataSources.put(db11, db1);
        DBTypeEnum db22 = DBTypeEnum.db2;
        targetDataSources.put(db22, db2);
        DBTypeEnum db33 = DBTypeEnum.db3;
        targetDataSources.put(db33, db3);
        DynamicDataSourceRouting dynamicDataSourceRouting = new DynamicDataSourceRouting();

        dynamicDataSourceRouting.setTargetDataSources(targetDataSources);
        //默认数据源【这都不用了】
//        dynamicDataSourceRouting.setDefaultTargetDataSource(defaultDatasource);
        //初始化DynamicDataSourceContextHolder的dataSourceIds
        //DBTypeEnum.db2的name() 就是db2
        //dataSourceIds存放的内容为 db1 db2 db3
        DynamicDataSourceContextHolder.dataSourceIds.addAll(Arrays.asList(db11.name(), db22.name(), db33.name()));
        return dynamicDataSourceRouting;
    }


    /**
     * 事务管理器
     */
    @Bean
    @Primary
    public PlatformTransactionManager transactionManager(@Qualifier("dynamicDataSource") DataSource dynamicDataSource) {
        return new DataSourceTransactionManager(dynamicDataSource);
    }
}
